#!/bin/bash
if [ -z $1 ]; then
    echo "Usage: start_mysql.sh <server_id>"
    echo "server_id: 1 or 2"
    exit 1
fi

MYSQL_DATA_ROOT="/var/lib"
MYSQL_LOG_ROOT="/var/log"
MYSQL_CONF_ROOT="$( pwd -P )"

echo "-----------------------start_mysql.sh----------------------"

yum -y install wget cmake gcc gcc-c++ ncurses ncurses-devel libaio libaio-devel openssl openssl-devel

yum -y install autoconf

if [ `grep "mysql" /etc/passwd | wc -l` -eq 0 ];then
echo "adding user mysql"
/usr/sbin/groupadd mysql
/usr/sbin/useradd -g mysql mysql
else
echo "mysql user is exist"
fi

MYSQL_SERVER_ID=$1
MYSQL_DATA_PATH="${MYSQL_DATA_ROOT}/mysql/data"
MYSQL_SOCK_PATH="${MYSQL_DATA_ROOT}/mysql/mysql.sock"
MYSQL_LOG_PATH="${MYSQL_LOG_ROOT}/mysql"
MYSQL_CONF_PATH="${MYSQL_CONF_ROOT}/my.cnf.d"

rm -rf ${MYSQL_DATA_PATH}

rm -rf ${MYSQL_SOCK_PATH}

if [ ! -d $MYSQL_DATA_PATH ]; then
    sudo mkdir -p ${MYSQL_DATA_PATH}
    sudo chown 1001:1001 ${MYSQL_DATA_PATH}
fi
if [ ! -d $MYSQL_LOG_PATH ]; then
    sudo mkdir -p ${MYSQL_LOG_PATH}
    sudo chown 1001:1001 ${MYSQL_LOG_PATH}
fi

sed "s|{{ SERVER_ID }}|$MYSQL_SERVER_ID|g" ${MYSQL_CONF_PATH}/my.cnf.template > ${MYSQL_CONF_ROOT}/my_bin/my.cnf

if [ ! -d /opt/mysql ]; then
    sudo mkdir /opt/mysql
fi

cp -rf ${MYSQL_CONF_ROOT}/my_bin/* /opt/mysql/

rm -f /etc/my.cnf

cp -f /opt/mysql/my.cnf /etc/my.cnf

rm -rf mysql-5.7.31-linux-glibc2.12-x86_64

mysql_file ="./mysql-5.7.31-linux-glibc2.12-x86_64.tar.gz"

if [ -f ${mysql_file} ];then
	echo  ${mysql_file} exists!
else
	wget https://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.31-linux-glibc2.12-x86_64.tar.gz
    echo ${file} not exists!
fi

echo "tar xzvf mysql-5.7.31-linux-glibc2.12-x86_64"
tar xzvf mysql-5.7.31-linux-glibc2.12-x86_64.tar.gz
rm -rf /usr/local/mysql
mv  mysql-5.7.31-linux-glibc2.12-x86_64 /usr/local/mysql


chown -R mysql:mysql /usr/local/mysql/
chown -R mysql.mysql ${MYSQL_DATA_PATH}/

chown -R mysql  /var/lib/mysql/

cd /usr/local/mysql

./bin/mysqld --initialize --user=mysql --datadir=${MYSQL_DATA_PATH} --basedir=/usr/local/mysql

cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld

chmod +x /etc/init.d/mysqld

chkconfig --add mysqld
chkconfig mysqld  on

echo -e "basedir = /usr/local/mysql\ndatadir = ${MYSQL_DATA_PATH}\n" >> /etc/my.cnf

echo "export PATH=$PATH:/usr/local/mysql/bin" > /etc/profile.d/mysql.sh
source /etc/profile.d/mysql.sh

echo "mysql starting"

service mysqld start 

if [ $? -ne 0 ];then
echo "mysql start filed ,please check it out!"
else
echo "mysql start successful,congratulations!"
fi